<template>
  <div class="game-comment">
    <header-top :option='headerOption'></header-top>
    <div class="container" ref='container' 
      @click.prevent='onShowEmoji(false)' 
      :style="{ paddingBottom: msgsPB }" 
      @touchstart='onTouchStart'
      @touchmove='onTouchMove'
      @touchend='onTouchEnd'>
      <div class='tip'>
        <div class='noMoreMsgs' v-if='noMoreMsgs && msgs.length !== 0'>
          <div class='line'></div>
          登顶评论巅峰啦>_<
          <div class='line'></div>
        </div>
        <div v-if='msgs.length === 0 && !isLoading' class="noMoreMsgs">啊咧>_<咋没有人评论？</div>
        <div class='isLoading' v-if='isLoading'>加载中...</div>
        <div class='isLoading' v-if='!isLoading && !noMoreMsgs && msgs.length !== 0'>下拉加载更多</div>
      </div>
      <div v-for='msg in msgs'  :key='msg.SERIAL_NO' >
        <div class="my" v-if='msg.USER_CODE == entryData.userCode'>
          <div class="user-wrap"></div>
          <div class="msg-wrap">
            <div class="up">
              <div class="msg">
                <div class="send-wrap">
                  <i class="iconfont icon-iconloading-copy" v-show='msg.isSending'/>
                  <i class="iconfont icon-warn" v-show='msg.failed' @click='resendMsg(msg)'/>
                </div>
                <div class='msg-html' v-html='msg.COMMUNITY_CONTENT'></div>
              </div>
              <div class="triangle"></div>
            </div>
            <div class="down">
              <span class="date" v-text='msg.COMMUNITY_DATE'></span>
              <span class="time" v-text='msg.COMMUNITY_TIME'></span>
            </div>
          </div>
          <div class="user-wrap" @click='onMyself(msg.USER_CODE)'>
            <div class="header-wrap" v-if='msg.VIP !== "1"'>
              <img class='header' v-bind:src="msg.USER_HEAD"/>
            </div>
            <div class='header-wrap vip' v-else>
              <img class='header' v-bind:src="msg.USER_HEAD"/>
            </div>
            <div class='name' v-text='msg.NICKNAME'></div>
          </div>
        </div>
        <div class="other" v-else>
          <div class="user-wrap" @click='onOther(msg.USER_CODE)'>
            <div class="header-wrap" v-if='msg.VIP !== "1"'>
              <img class='header' v-bind:src="msg.USER_HEAD"/>
            </div>
            <div class='header-wrap vip' v-else>
              <img class='header' v-bind:src="msg.USER_HEAD"/>
            </div>
            <div class='name' v-text='msg.NICKNAME'></div>
          </div>
          <div class="msg-wrap">
            <div class="up">
              <div class="triangle"></div>
              <div class="msg">
                <div class='msg-html' v-html='msg.COMMUNITY_CONTENT'></div>
              </div>
            </div>
            <div class="down">
              <span class="date" v-text='msg.COMMUNITY_DATE'></span>
              <span class="time" v-text='msg.COMMUNITY_TIME'></span>
            </div>
          </div>
          <div class="user-wrap"></div>
        </div>
      </div>
    </div>
    <div class="chat-bottom-wrap" v-show='allowChat' ref='chat' >
      <div class='loadNewIcon'>
        <img :src="loadNewIcon" v-if='!isLoadingNew && msgs.length != 0 && !showNoNewMsg' @click='onLoadNew'>
        <div v-show='isLoadingNew'>
          <i class="iconfont icon-iconloading-copy" />
          加载新评论中...
        </div>
        <div v-if='showNoNewMsg'>啊咧>_<没有新评论</div>
      </div>
      <speak
        :visible.sync='isInTalkTime'
        ref='speak'
        @speaking='append2Msgs'
        :options='entryData'
        @emojiVisible='onEmojiVisible'/>
    </div>
  </div>
</template>

<script>
import LocalDAO from 'common/localDAO'
import RemoteDAO from 'common/remoteDAO'
import Constant from 'common/constant'
import CommonUtil from 'common/common.util.js'
import HeaderTop from 'components/HeaderTop'
import Speak from 'components/game/comment/Speak'
import EmojiUtil from 'components/game/comment/EmojiUtil'
export default {
  components:{ HeaderTop, Speak },
  data(){
    return {
      emojiUtil: null,
      //基本信息
      myUserHead: '',
      myNickName: '',
      myDefaultHIndex: 1,
      headerOption: {
        title: '评论',
        leftBtn: Constant.leftBtn.BACK,
        operations: []
      },
      
      msgs:[],
      prePosIndex:0,//评论列表顶部第一条消息的offsetTop

      pullText: '下拉加载更多',
      dropText: '释放加载更多',
      noMoreMsgs: false,
      isInit: true,//是否为第一次加载msgs
      //input area
      isInTalkTime: true,
      //url传入的数据,同时也作为传入speak组件的options
      entryData:{
        showEmoji: false,//控制表情框的显示
        userCode: '',//用户代码，通常是当前聊天用户的
        page_no: 1,
        size: 20,//分页的页大小
        objectType: 4,//业务类型  1：人员  2：系统   3：组合  4：比赛  5：产品
        topicCode:'',//当OBJECT_TYPE为3时，填入对应的组合代码  为4时，是比赛ID  为5时，输入产品的代码
        topicName:'',//当OBJECT_TYPE为3时，填入对应的组合名称
        identity: Constant.game.identity.PLAYER,//当前用户的角色， onlooker-未参赛
        gameStep: '4',//比赛的进程,默认为4:比赛已结束
        queryFlag: 0,//查询标志   1：查询个人   0或空：查询这个比赛的所有评论，此时GAME_ID不能为空
        style: 'white'
      },
      msgsPB: '47px',
      scrollPosition: 0,
      isLoading: false,
      loadNewIcon: require('assets/images/game/load-more.png'),
      isLoadingNew: false,
      touchStartY: 0,
      touchEndY: 0,
      showNoNewMsg: false, //显示没有新消息的提示
      showNoNewTimer: null,
      hasTouchMove: false
    }
  },
  computed: {
    allowChat: function () {
      if (this.entryData.identity === Constant.game.identity.PLAYER && 
        this.entryData.gameStep !== '4' && 
        this.entryData.gameStep !== '5' &&
        this.isInTalkTime) return true
      return false
    }
  },
  mounted(){
    // this.msgsPB = this.$refs.chat.offsetHeight + 'px';
    this.initData();
    this.getMsgs();
  },
  methods: {
    onOther (othersUserCode) {
      this.$router.push({path: '/otherdetail', query: {userCode: othersUserCode}})
    },
    onMyself (minieUserCode) {
      this.$router.push({path:'/selfdetail'})
    },
    onTouchStart (evt) {
      this.hasTouchMove = false
      if (evt.changedTouches.length <= 0) return
      this.touchStartY = evt.changedTouches[0].pageY
    },
    onTouchMove (evt) {
      this.hasTouchMove = true
    },
    onTouchEnd (evt) {
      if (evt.changedTouches.length <= 0 || !this.hasTouchMove) return
      this.touchEndY = evt.changedTouches[0].pageY
      if ((this.touchStartY - this.touchEndY) >= 0) return //页面向下滚动，用户查看底部消息
      //页面向上滚动，用户查看历史消息
      if (this.$refs.container.scrollTop <= 200) {
        this.scrollPosition = this.$refs.container.scrollHeight - this.$refs.container.scrollTop
        this.getMsgs()
      }
      this.hasTouchMove = false
    },
    onEmojiVisible(visible){
      if (this.$refs.chat == undefined) return
      this.msgsPB = ( this.$refs.chat.scrollHeight + 2 ) + 'px';
    },
    onShowEmoji(visible){
      this.$store.dispatch('setEmojiVisible', visible);
      this.$nextTick(() => {
        this.onEmojiVisible(visible);
      });
    },
    initData(){
      this.entryData.userCode = LocalDAO.getUserCode();
      this.myUserHead = LocalDAO.getUserHead();
      this.myNickName = LocalDAO.getNickname();
      this.myDefaultHIndex = this.entryData.userCode % 8 + 1;

      Object.assign(this.entryData, this.$route.query);
      
    },
    resendMsg(msg){
      this.$refs.speak.sendMsg(msg, true);
    },
    onLoadNew () {
      if ( this.isLoadingNew) return
      this.isLoadingNew = true;
      var params = {
        ID: this.entryData.topicCode,
        PAGE_SIZE: this.entryData.size,
        PAGE_NO: 1,
        QUERY_FLAG: this.entryData.queryFlag
      }
      RemoteDAO.callUC12008318(params, (resp) => {
        if (parseInt(resp.error) == 0) {
          if (resp.data.body.length <= 0){
            // this.$store.dispatch('setTip', {text: '啊咧>_<没有新消息'})
            this.showNoNewTip()
          } else {
            this.mergeNewMsgs(resp.data.body)
          }
        }
        this.isLoadingNew = false
      })
    },
    mergeNewMsgs (newMsgs) {
      var lastSerialNo = this.msgs[this.msgs.length - 1].SERIAL_NO
      var findPos = false
      for(let i = newMsgs.length - 1; i >= 0; i--){
        if (findPos) {
          newMsgs[i] = this.formatMsg(newMsgs[i])
          this.msgs.push(newMsgs[i])
        } else {
          if (lastSerialNo == newMsgs[i].SERIAL_NO && i != 0 ) findPos = true
        }
      }
      // if (!findPos) this.$store.dispatch('setTip', {text: '啊咧>_<没有新消息'})
      if (!findPos) this.showNoNewTip()
    },
    showNoNewTip () {
      this.showNoNewMsg = true
      if (this.showNoNewTimer != null) {
        clearTimeout(this.showNoNewTimer)
        this.showNoNewTimer = null
      }
      this.showNoNewTimer = setTimeout(() => {
        this.showNoNewMsg = false
      }, 900)
    },
    getMsgs(){
      // if(this.msgs.length > 0) this.prePosIndex = this.msgs.length - 1;
      if(this.noMoreMsgs || this.isLoading) {
        // this.$refs.loadmore.onTopLoaded();
        console.info('isLoading',this.isLoading)
        return;
      }
      this.isLoading = true
      var params = {
        ID: this.entryData.topicCode,
        PAGE_SIZE: this.entryData.size,
        PAGE_NO: this.entryData.page_no,
        QUERY_FLAG: this.entryData.queryFlag
      }
      RemoteDAO.callUC12008318(params, (resp) => {
        if(parseInt(resp.error) != 0) {
          this.dataStatus = resp.data; //Error
          this.$store.dispatch('setTip', {text: resp.data});
        }else {
          console.info('msgs', resp);
          if(resp.data.body.length <= 0){
            this.noMoreMsgs = true;
            this.dropText = '巅峰状态';
            this.pullText = '巅峰状态';
          }else{
              this.unshiftMsgs(resp.data.body);
              this.entryData.page_no += 1;
              this.$nextTick(()=>{
                if(this.isInit){
                  this.isInit = false;
                  this.scroll2Bottom();
                }else{
                  this.$refs.container.scrollTop = this.$refs.container.scrollHeight - this.scrollPosition
                }
              });
          }
        }
        this.isLoading = false
      });
    },
    formatMsg (msg) {
      msg.COMMUNITY_DATE = msg.COMMUNITY_DATE.substring(4, 6) + '-' + msg.COMMUNITY_DATE.substring(6, 8)
      if (msg.COMMUNITY_TIME.length === 5) msg.COMMUNITY_TIME = '0' + msg.COMMUNITY_TIME
      msg.COMMUNITY_TIME = msg.COMMUNITY_TIME.substring(0, 2) + ':' + msg.COMMUNITY_TIME.substring(2, 4)
      msg.DEFAULT_HEAD_INDEX = msg.USER_CODE % 8 + 1
      if(msg.USER_HEAD === undefined || msg.USER_HEAD.length == 0){
        if(msg.USER_CODE == this.entryData.userCode) msg.USER_HEAD = this.myUserHead;
        else msg.USER_HEAD = 'https://dl.app.gtja.com/pictures/niutou/tou'+ msg.DEFAULT_HEAD_INDEX +'@2x.png';
      }
      msg['COMMUNITY_CONTENT_TEXT'] = msg.COMMUNITY_CONTENT;
      msg.COMMUNITY_CONTENT = msg.COMMUNITY_CONTENT.replace(/\\u/g, '\%u');
      msg.COMMUNITY_CONTENT = unescape(msg.COMMUNITY_CONTENT)
      if (!this.emojiUtil) this.emojiUtil = new EmojiUtil()
      msg.COMMUNITY_CONTENT = this.emojiUtil.str2Emoji(msg.COMMUNITY_CONTENT);
      return msg
    },
    unshiftMsgs(data){
      if(data == undefined || data == null) return data;
      var newMsgs = []
      for(let i = 0; i < data.length; i++){
        data[i].COMMUNITY_DATE = data[i].COMMUNITY_DATE.substring(4,6)+'-'+data[i].COMMUNITY_DATE.substring(6,8);
        if(data[i].COMMUNITY_TIME.length == 5) data[i].COMMUNITY_TIME = '0'+data[i].COMMUNITY_TIME;
        data[i].COMMUNITY_TIME = data[i].COMMUNITY_TIME.substring(0,2) +':'+ data[i].COMMUNITY_TIME.substring(2,4);
        data[i].DEFAULT_HEAD_INDEX = data[i].USER_CODE % 8 + 1;
        if(data[i].USER_HEAD === undefined || data[i].USER_HEAD.length == 0){
          if(data[i].USER_CODE == this.entryData.userCode) data[i].USER_HEAD = this.myUserHead;
          else data[i].USER_HEAD = 'https://dl.app.gtja.com/pictures/niutou/tou'+ data[i].DEFAULT_HEAD_INDEX +'@2x.png';
        }
        data[i]['COMMUNITY_CONTENT_TEXT'] = data[i].COMMUNITY_CONTENT;
        data[i].COMMUNITY_CONTENT = data[i].COMMUNITY_CONTENT.replace(/\\u/g, '\%u');
        data[i].COMMUNITY_CONTENT = unescape(data[i].COMMUNITY_CONTENT);
        if (!this.emojiUtil) this.emojiUtil = new EmojiUtil()
        data[i].COMMUNITY_CONTENT = this.emojiUtil.str2Emoji(data[i].COMMUNITY_CONTENT);
        newMsgs.unshift(data[i]);
      }
      this.msgs= newMsgs.concat(this.msgs)
    },    
    /**
     * 将发送的消息加入msgs列表
     * 
     * @param  {[type]} msg [description]
     * @return {[type]}     [description]
     */
    append2Msgs(msg){
      let text = msg.text.replace(/\\u/g, '\%u');
      text = unescape(text);
      msg['DEFAULT_HEAD_INDEX'] = this.myDefaultHIndex;
      msg['USER_CODE'] = this.entryData.userCode;
      msg['USER_HEAD'] = this.myUserHead;
      msg['NICKNAME'] = this.myNickName;
      switch(msg.type){
        case 1: //emoji
          msg['COMMUNITY_CONTENT'] = '<img class="emoji_item" src="'+ msg.path +'" />';
          break;
        default:
          msg['COMMUNITY_CONTENT'] = text;
      }
      this.msgs.push(msg);
      this.$nextTick(()=>{this.scroll2Bottom()});
    },
    scroll2Bottom(){
      this.$refs.container.scrollTop = this.$refs.container.scrollHeight + 10;
    }
  }

}
</script>

<style scoped>
  .chat-bottom-wrap{
    position: fixed;
    bottom: 0;
    width: 100%;
    z-index: 5;
  }

  .container{
    background-color: #f2f2f7;
    position: absolute;
    top: 44px;
    bottom: 0;
    width: 100%;
    overflow: auto;
    padding-top: 20px;
    padding-bottom: 20px;
    -webkit-overflow-scrolling: touch;
  }
  .tip{
    position: absolute;
    top: 0px;
    left: 0;
    width: 100%;
  }
  .noMoreMsgs{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .noMoreMsgs .line{
    flex: 1;
    border-top: solid 1px #ddd;
    margin: auto 10px;
  }
  .isLoading, .noMoreMsgs{
    text-align: center;
    color: #999;
    margin: 10px;
    position: relative;
    text-align: center;
  }
  .my, .other{
    display: flex;
    margin: 18px auto;
  }
  .my .triangle{
    border-bottom: 10px solid #E3E7F2;
    border-right: 10px solid #F2F3F7;
    display: inline-block;
    vertical-align: bottom;
  }
  .other .triangle{
    border-bottom: 10px solid #43A7FF;
    border-left: 10px solid #F2F3F7;
    display: inline-block;
    vertical-align: bottom;
  }
  .msg-wrap{
    flex: 7;
    display: flex;
    flex-direction: column;
    margin: auto 18px;
  }
  .up{
    display: flex;
    flex-direction: row;
  }
  .my .up{
    justify-content: flex-end;
  }
  .send-wrap{
    align-self: flex-end;
  }
  .icon-warn{
    color: red;
  }
  .msg{
    flex: 1;
    position: relative;
    display: flex;
  }
  .my .msg{
    justify-content: flex-end;
  }
  .my .msg-html{
    word-wrap: break-word;
    word-break: normal;
    background-color: #E3E7F2;
    padding: 8px;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    border-bottom-left-radius: 5px;
    text-align: left;
    margin-right: -6px;
  }
  .my .down{
    text-align: right;
  }
  .down{
    color: #959595;
    margin-top: 5px;
    font-size: 0.9rem;
  }
  .other .msg-html{
    word-wrap: break-word;
    word-break: normal;
    background-color: #43A7FF;
    padding: 8px;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
    text-align: left;
    color: #fff;
    margin-left: -6px;
  }

  .user-wrap{
    /*flex: 1;*/
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    align-items: center;
    width: 36px;
    z-index: 2;
  }
  .header-wrap{
    position: relative;
  }
  .vip:after{
    content: 'v';
    background-color: #ff1f1f;
    display: block;
    color: #fff;
    font-size: 12px;
    border-radius: 50%;
    line-height: 10px;
    text-align: center;
    width: 12px;
    height: 12px;
    position: absolute;
    right: 0;
    bottom: 0;
    border: solid 1px #fff;
  }
  .header{
    width: 100%;
    max-width: 44px;
    border-radius: 50%;
  }
  .name{
    max-width: 36px;
    color: black;
    font-size: 0.9rem;
    min-height: 12px;
    white-space: nowrap;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    overflow: hidden;
    text-align: center;
    margin-top: 5px;
  }
  .loadNewIcon {
    text-align: center;
    color: #999;
    margin-bottom: 10px;
  }
  .loadNewIcon img{
    width: 10px;
  }
</style>